import prisma from '../config/prisma';
import { User, CreateUserRequest, UpdateUserRequest } from '../models/User';
import bcrypt from 'bcrypt';
import { generateTimestampNumericUUID } from '../utils/uuid';
import { DEFAULT_PASSWORD } from '../const';

export class UserService {
  // 获取所有用户
  static async getAllUsers(): Promise<User[]> {
    const users = await prisma.user.findMany({
      orderBy: {
        createdAt: 'desc',
      },
    });

    return users as unknown as User[];
  }

  // 获取用户ById
  static async getUserById(id: string): Promise<User | null> {
    const user = await prisma.user.findUnique({
      where: {
        id: id,
      },
    });

    return user as User | null;
  }

  // 根据邮箱获取用户（用于登录）
  static async getUserByEmail(email: string): Promise<User | null> {
    const user = await prisma.user.findFirst({
      where: {
        email,
        status: {
          not: 0,
        },
      },
    });

    return user as User | null;
  }

  // 创建用户
  static async createUser(userData: CreateUserRequest): Promise<User> {
    const hashedPassword = await bcrypt.hash(DEFAULT_PASSWORD, 10);

    const userId = generateTimestampNumericUUID();

    const user = await prisma.user.create({
      data: {
        id: userId,
        name: userData.name,
        email: userData.email,
        password: hashedPassword,
        avatar: userData.avatar,
        position: userData.position,
        phone: userData.phone,
        gender: userData.gender,
        birthday: userData.birthday,
        bio: userData.bio,
        role: userData.role
      },
    });

    return user as unknown as User;
  }

  // 更新用户
  static async updateUser(userData: UpdateUserRequest): Promise<User | null> {
    // 验证id是否存在
    if (!userData.id) {
      throw new Error('更新操作需要用户ID');
    }

    const updateData: any = {};

    // 动态构建更新字段，排除id字段
    Object.entries(userData).forEach(([key, value]) => {
      if (value !== undefined && key !== 'id') {
        updateData[key] = value;
      }
    });

    if (Object.keys(updateData).length === 0) return null;

    const user = await prisma.user.update({
      where: {
        id: userData.id,
      },
      data: updateData,
    });

    return user as unknown as User;
  }

  // 删除用户
  static async deleteUser(id: string): Promise<boolean> {
    // 参数类型改为string
    const result = await prisma.user.delete({
      where: {
        id: id,
      },
    });

    return result !== null;
  }

  // 用户登录
  static async login(email: string, password: string): Promise<User | null> {
    const user = await this.getUserByEmail(email);
    if (!user) return null;

    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) return null;

    // 更新登录信息
    await this.updateLoginInfo(user.id);

    return user;
  }

  // 更新登录信息
  private static async updateLoginInfo(userId: string): Promise<void> {
    // 参数类型改为string
    await prisma.user.update({
      where: {
        id: userId,
      },
      data: {
        lastLoginAt: new Date(),
        loginCount: {
          increment: 1,
        },
      },
    });
  }

  // 重置密码
  static async resetPassword(userId: string): Promise<void> {
    // 参数类型改为string
    const hashedPassword = await bcrypt.hash(DEFAULT_PASSWORD, 10);

    await prisma.user.update({
      where: {
        id: userId,
      },
      data: {
        password: hashedPassword,
      },
    });
  }

  // 修改密码
  static async changePassword(
    userId: string,
    oldPassword: string,
    newPassword: string
  ) {
    // 参数类型改为string
    const user = await this.getUserById(userId);
    if (!user) throw new Error('用户不存在');

    const isValidPassword = await bcrypt.compare(oldPassword, user.password);
    if (!isValidPassword) throw new Error('旧密码错误');

    const hashedPassword = await bcrypt.hash(newPassword, 10);

    await prisma.user.update({
      where: {
        id: userId,
      },
      data: {
        password: hashedPassword,
      },
    });
    return true;
  }
}
